package com.example.xungeng2.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xungeng2.common.BaseContext;
import com.example.xungeng2.common.Result;
import com.example.xungeng2.pojo.TaskPoint;
import com.example.xungeng2.pojo.User;
import com.example.xungeng2.service.TaskPointService;
import com.example.xungeng2.service.UserService;
import com.example.xungeng2.service.WorkerService;
import com.example.xungeng2.unknow.TableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/taskpoint")
public class TaskPointController {
    @Autowired
    private TaskPointService taskPointService;

    @Autowired
    private WorkerService workerService;

    @Autowired
    private UserService userService;


    @Cacheable(value = "taskPoint",key = "'selectAll'")
    @GetMapping("selectAll")
    public Result selectAll(HttpSession session){
        List<TaskPoint> list = taskPointService.selectAllPoint();
        System.out.println(list);
        return Result.ok(list);
    }

    @CacheEvict(value = "taskPoint",allEntries = true)
    @PostMapping("insertPoint")
    public Result insertPoint(@RequestBody TaskPoint taskPoint){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        taskPoint.setCreateTime(df.format(new Date()));
        taskPoint.setUpdateTime(df.format(new Date()));
        boolean flag = taskPointService.save(taskPoint);
        long id = Thread.currentThread().getId();
        System.out.println(id);
        BaseContext.setTaskPointId(taskPoint.getTaskId());
        if (flag) {
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    @CacheEvict(value = "taskPoint",allEntries = true)
    @DeleteMapping("/undefined")
    public Result deletePoint(TaskPoint taskPoint){
        long id = Thread.currentThread().getId();
        System.out.println(id);
        Integer pointId = BaseContext.getPointId();
        System.out.println(pointId);
        taskPointService.deletePoint(pointId);
        return Result.ok();
    }
    @CacheEvict(value = "taskPoint",allEntries = true)
    @PostMapping("/updatePoint")
    public Result updatePoint(@RequestBody TaskPoint taskPoint){
        System.out.println(taskPoint.toString());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String updateDate = dateFormat.format(new Date());
        taskPoint.setUpdateTime(updateDate);
        boolean b = taskPointService.updateById(taskPoint);
        return Result.ok();
    }
    @GetMapping("clockPoint/{userId}/{taskId}")
    public Result userClockRWPoint(@PathVariable("userId") int userId,
                                   @PathVariable("taskId") int taskId){
        boolean flag = taskPointService.clockPoint(taskId, userId);
        if (flag) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    /**
     * 分配任务点
     * @return
     */
    @PostMapping("/allotPoint")
    public Result allotPoint(){
        Result result = new Result();
        List<String> users = new ArrayList();
        List<String> points = new ArrayList<>();
        users.add("1");
        users.add("2");
        points.add("1");
        points.add("2");
        List<String> users11 = new ArrayList<>();
        List<String> points11 = new ArrayList<>();
        for (int i=0;i<users.size()-1;i++){
            users11.add(users.get(i));
        }

        for (int j=0;j<points.size()-1;j++){
            points11.add(points.get(j));
        }

        for (int i=0;i<users11.size();i++){
            workerService.createUserTask(Integer.parseInt(users.get(i)));
            User user = userService.selectUserById(users11.get(i));
            if (user.getIsAssigned()==1){
                result.setMessage("该巡更人员已被派遣！！");
                result.setCode(203);
                break;
            }
            for (int j=0;j<points11.size();j++){
                //查看该巡更人员是否已被分配该点位
                boolean b = taskPointService.selectUserPoint(users.get(i), points.get(j));
                if (b){
                    workerService.updateUserTaskNum(Integer.parseInt(users.get(i)));
                    taskPointService.allotPoint(users.get(i), points.get(j));
                    //更改巡更人员状态为已被派遣
                    userService.changeUserState(users.get(i));
                    //更改任务点状态及任务点分配时间
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    taskPointService.changePointState(points.get(j), df.format(new Date()));
                    result.setMessage("派遣成功");
                    result.setCode(200);
                }else {
                    result.setMessage("该任务点已经派遣！！");
                    result.setCode(202);
                    break;
                }
            }
        }
        return result;
    }

    @GetMapping("/selectPageAll")
    public TableMap getPageTasks(Long page,Long limit){
        Page<TaskPoint> pointPage = taskPointService.selectPageAll(page,limit);
        TableMap tableMap = new TableMap();
        tableMap.setData(pointPage.getRecords());
        tableMap.setCount(pointPage.getTotal());
        return tableMap;
    }

    @PostMapping("/deletePoint")
    public Result deleteThisPoint(@RequestBody TaskPoint taskPoint){
        taskPointService.deleteThisPoint(taskPoint);
        return Result.ok();
    }
}
